<script setup>
// 定义页面元数据
definePageMeta({
  middleware: 'auth',
  layout: 'default'
})

// 表格头部配置
const headers = [
    {
        title: '订单编号',
        key: 'order_sn',
        sortable: false
    },
    {
        title: '订单名称',
        key: 'title',
        sortable: false
    },
    {
        title: '商品名称',
        key: 'goods_name',
        sortable: false
    },
    {
        title: '类型',
        key: 'type',
        sortable: false
    },
    {
        title: '邮箱',
        key: 'email',
        sortable: false
    },
    {
        title: '实付金额',
        key: 'actual_price',
        sortable: false
    },
    {
        title: '状态',
        key: 'status',
        sortable: false
    },
    {
        title: '创建时间',
        key: 'created_at',
        sortable: false
    }
]

// 响应式数据
const loading = ref(false)
const orders = ref([])
const pagination = ref({
  page: 1,
  limit: 20,
  total: 0,
  pages: 0
})

// 查询条件
const searchForm = ref({
  order_sn: '', // 订单编号
  title: '', // 订单名称
  email: '', // 邮箱
  status: '' // 状态
})

// 状态选项
const statusOptions = [
  { value: '', text: '全部状态' },
  { value: '1', text: '待支付' },
  { value: '2', text: '待处理' },
  { value: '3', text: '处理中' },
  { value: '4', text: '已完成' },
  { value: '5', text: '处理失败' },
  { value: '6', text: '异常' },
  { value: '-1', text: '已过期' }
]

/**
 * 获取订单状态的颜色变体
 * @param {string} status - 状态文本
 * @returns {string} 颜色变体
 */
const resolveOrderStatusVariant = (status) => {
  const statusLowerCase = status.toLowerCase()
  if (statusLowerCase === '待支付') return 'warning'
  if (statusLowerCase === '待处理') return 'info'
  if (statusLowerCase === '处理中') return 'primary'
  if (statusLowerCase === '已完成') return 'success'
  if (statusLowerCase === '处理失败') return 'error'
  if (statusLowerCase === '异常') return 'error'
  if (statusLowerCase === '已过期') return 'secondary'
  return 'secondary'
}

/**
 * 获取订单类型的颜色和图标
 * @param {string} type - 类型文本
 * @returns {object} 包含颜色和图标的对象
 */
const resolveOrderTypeVariant = (type) => {
  if (type === '自动发货') {
    return {
      color: 'success',
      icon: 'ri-robot-line'
    }
  }
  if (type === '人工处理') {
    return {
      color: 'warning',
      icon: 'ri-user-settings-line'
    }
  }
  return {
    color: 'secondary',
    icon: 'ri-question-line'
  }
}

/**
 * 查询订单数据
 * @param {number} page - 页码
 */
const fetchOrders = async (page = 1) => {
  try {
    loading.value = true
    
    // 获取认证信息
    const { $auth } = useNuxtApp()
    
    // 构建查询参数
    const params = {
      page,
      limit: pagination.value.limit,
      ...searchForm.value
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '') {
        delete params[key]
      }
    })
    
    const response = await $fetch('/api/orders', {
      method: 'GET',
      query: params,
      headers: {
        'Authorization': `Bearer ${$auth.token}`
      }
    })
    
    // 检查响应格式
    if (response.success && response.data) {
      orders.value = response.data.orders
      pagination.value = response.data.pagination
    } else {
      console.error('API响应格式错误:', response)
      // 可以添加用户友好的错误提示
    }
    
  } catch (error) {
    console.error('获取订单数据失败:', error)
    
    // 如果是认证错误，重定向到登录页
    if (error.statusCode === 401 || error.statusCode === 403) {
      $auth.logout()
      await navigateTo('/login')
    }
    // 这里可以添加错误提示
  } finally {
    loading.value = false
  }
}

/**
 * 搜索订单
 */
const handleSearch = () => {
  pagination.value.page = 1
  fetchOrders(1)
}

/**
 * 重置搜索条件
 */
const handleReset = () => {
  searchForm.value = {
    order_sn: '',
    title: '',
    email: '',
    status: ''
  }
  pagination.value.page = 1
  fetchOrders(1)
}

/**
 * 格式化日期时间
 * @param {string} dateTime - 日期时间字符串
 * @returns {string} 格式化后的日期时间
 */
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

/**
 * 格式化金额
 * @param {number} amount - 金额
 * @returns {string} 格式化后的金额
 */
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '¥0.00'
  return `¥${Number(amount).toFixed(2)}`
}

// 页面加载时获取数据
onMounted(() => {
  fetchOrders()
})
</script>

<template>
  <div>
    <!-- 页面标题 -->
    <div class="d-flex justify-space-between align-center mb-6">
      <h1 class="text-h4 font-weight-bold">订单管理</h1>
    </div>

    <!-- 查询条件表单 -->
    <VCard class="mb-6">
      <VCardTitle class="pb-4">
        <VIcon icon="ri-search-line" class="me-2" />
        查询条件
      </VCardTitle>
      
      <VCardText>
        <VRow>
          <VCol cols="12" md="3">
            <VTextField
              v-model="searchForm.order_sn"
              label="订单编号"
              placeholder="请输入订单编号"
              clearable
              prepend-inner-icon="ri-hashtag"
            />
          </VCol>
          
          <VCol cols="12" md="3">
            <VTextField
              v-model="searchForm.title"
              label="订单名称"
              placeholder="请输入订单名称"
              clearable
              prepend-inner-icon="ri-file-text-line"
            />
          </VCol>
          
          <VCol cols="12" md="3">
            <VTextField
              v-model="searchForm.email"
              label="邮箱"
              placeholder="请输入邮箱地址"
              clearable
              prepend-inner-icon="ri-mail-line"
            />
          </VCol>
          
          <VCol cols="12" md="3">
            <VSelect
              v-model="searchForm.status"
              label="订单状态"
              :items="statusOptions"
              item-title="text"
              item-value="value"
              clearable
              prepend-inner-icon="ri-flag-line"
            />
          </VCol>
        </VRow>
        
        <VRow class="mt-2">
          <VCol cols="12" class="d-flex gap-4">
            <VBtn
              color="primary"
              prepend-icon="ri-search-line"
              @click="handleSearch"
              :loading="loading"
            >
              查询
            </VBtn>
            
            <VBtn
              variant="outlined"
              prepend-icon="ri-refresh-line"
              @click="handleReset"
            >
              重置
            </VBtn>
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- 订单数据表格 -->
    <VCard>
      <VCardTitle class="d-flex justify-space-between align-center">
        <div class="d-flex align-center">
          <VIcon icon="ri-list-check-3" class="me-2" />
          订单列表
          <VChip
            v-if="pagination.total > 0"
            size="small"
            color="primary"
            class="ms-3"
          >
            共 {{ pagination.total }} 条
          </VChip>
        </div>
      </VCardTitle>
      
      <VDataTable
        :headers="headers"
        :items="orders"
        :loading="loading"
        :items-per-page="pagination.limit"
        :page="pagination.page"
        item-value="id"
        class="text-no-wrap"
        fixed-header
        height="600"
        loading-text="正在加载订单数据..."
        no-data-text="暂无订单数据"
      >
        <!-- 订单编号 -->
        <template #item.order_sn="{ item }">
          <div class="d-flex align-center">
            <VIcon icon="ri-hashtag" size="16" class="me-2 text-medium-emphasis" />
            <span class="font-weight-medium text-primary">{{ item.order_sn }}</span>
          </div>
        </template>
        
        <!-- 订单名称 -->
        <template #item.title="{ item }">
          <div class="text-truncate" style="max-width: 200px;" :title="item.title">
            {{ item.title }}
          </div>
        </template>
        
        <!-- 商品名称 -->
        <template #item.goods_name="{ item }">
          <div class="text-truncate" style="max-width: 150px;" :title="item.goods_name">
            {{ item.goods_name }}
          </div>
        </template>
        
        <!-- 订单类型 -->
        <template #item.type="{ item }">
          <div class="d-flex align-center gap-2">
            <VIcon
              :icon="resolveOrderTypeVariant(item.type).icon"
              :color="resolveOrderTypeVariant(item.type).color"
              size="18"
            />
            <span class="text-sm">{{ item.type }}</span>
          </div>
        </template>
        
        <!-- 邮箱 -->
        <template #item.email="{ item }">
          <div class="d-flex align-center">
            <VIcon icon="ri-mail-line" size="16" class="me-2 text-medium-emphasis" />
            <span class="text-sm">{{ item.email }}</span>
          </div>
        </template>
        
        <!-- 实付金额 -->
        <template #item.actual_price="{ item }">
          <div class="d-flex align-center">
            <VIcon icon="ri-money-cny-circle-line" size="16" class="me-1 text-success" />
            <span class="font-weight-medium text-success">{{ formatAmount(item.actual_price) }}</span>
          </div>
        </template>
        
        <!-- 订单状态 -->
        <template #item.status="{ item }">
          <VChip
            :color="resolveOrderStatusVariant(item.status)"
            size="small"
            variant="tonal"
          >
            {{ item.status }}
          </VChip>
        </template>
        
        <!-- 创建时间 -->
        <template #item.created_at="{ item }">
          <div class="d-flex align-center">
            <VIcon icon="ri-time-line" size="16" class="me-2 text-medium-emphasis" />
            <span class="text-sm">{{ formatDateTime(item.created_at) }}</span>
          </div>
        </template>
        
        <!-- 分页 -->
        <template #bottom>
          <div class="d-flex justify-center pa-4" v-if="pagination.pages > 1">
            <VPagination
              v-model="pagination.page"
              :length="pagination.pages"
              :total-visible="7"
              @update:model-value="fetchOrders"
            />
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>

<style lang="scss" scoped></style>